package com.atguigu.day26.dml02;

import org.junit.Test;

import java.sql.*;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;
/*
查询部门表获取每一条记录 将每一条记录封装为对象 存到集合内
对集合进行遍历
 */
public class QueryExer {

    @Test
    public void test() throws Exception {
        //创建驱动
        //建立连接
        Connection connection = DriverManager.getConnection("jdbc:mysql:///atguigu", "root", "1234");
        //提供sql
        String sql = "select * from t_department";
        //创建命令发射器
        PreparedStatement pst = connection.prepareStatement(sql);
        //执行命令获取结果
        ResultSet rs = pst.executeQuery();
        //创建封装对象
        ArrayList<Description> arr = new ArrayList<>();
        //打印结果
        while (rs.next()) {
            Integer did = rs.getInt(1);
            String dname = rs.getString(2);
            String desc = rs.getString(3);
            //7.封装到集合中
            Description description = new Description(did, dname, desc);
            arr.add(description);
        }
        //遍历集合
        arr.forEach(System.out::println);
        System.out.println("---------------------------------------------------------------");
        //map: key->did value->dname+desc
        /*Map<Integer, Description> map = arr.stream().collect(Collectors.toMap(new Function<Description, Integer>() {
            @Override
            public Integer apply(Description description) {
                return description.getId();
            }
        }, new Function<Description, Description>() {
            @Override
            public Description apply(Description description) {
                return description;
            }
        }));*/

        Map<Integer, Description> map = arr.stream().collect(
                Collectors.toMap(Description::getId,d->d));

        map.forEach((k,v)-> System.out.println(k + "," + v));

        /*map.forEach(new BiConsumer<Integer, Description>() {
            @Override
            public void accept(Integer k, Description v) {
                System.out.println(k + "," + v);
            }
        });*/

        //关闭资源
        rs.close();
        pst.close();
        connection.close();
    }

}
